const conn = require('../db/config')

exports.all = (req,res) => {
    var sql = 'select * from syspersonlist'
    var page = req.query.offset || 0
    var limit = req.query.limit || 5
    conn.query(sql,(err,data)=>{
        if(err){
            return res.send('错误')
        }
        conn.query('select * from syspersonlist LIMIT '+ limit +' offset '+ page,(err,result) => {
            if(err) return res.send(err)
            if(result.length) res.send({data:result,total:data.length})
        })
    })
}

exports.search = (req,res) => {
    var name = "'"+req.query.search+"'"
    conn.query('select * from syspersonlist where name ='+name,(err,result) => {
        if(err) return res.send(err)
        if(result.length) res.send({data:result, status:200})
        else res.send({msg:'未找到', status:500})
    })
}

exports.setnew = (req,res) => {
    req.query.isadmin = req.query.isadmin==='false'?0:1
    var userdata = "('"+req.query.name+"','"+req.query.telphone+"','"+req.query.email+"','"+req.query.isadmin+"')"
    //添加前先判断用户是否存在于数据库中，若已存在则返回警告信息
    conn.query('select * from syspersonlist where name ="'+req.query.name+'"',(err,row) => {
        if(err)  return console.log(err)
        if(row.length) return res.send({msg:'该用户名已存在请勿重复添加！',status:400})
        else 
        conn.query('insert INTO syspersonlist (name,telphone,email,isadmin) VALUES '+userdata,(err,result) => {
            if(err) return res.send({msg:'添加失败，数据库出错',status:500})
            else res.send({msg:'添加成功！', status:200})
        })
    })
}

exports.updataold = (req,res) => {
    req.query.isadmin = req.query.isadmin==='false'?0:1
    var sql = 'select * from syspersonlist where name ="'+req.query.name+'"and telphone = "'+req.query.telphone+'" and email = "'+req.query.email+'" and isadmin = '+req.query.isadmin
    conn.query(sql,(err,row) => {
        if(err)  return console.log(err)
        if(row.length) return res.send({msg:'您未修改任何数据!',status:400})
        else {
            //获取传入行中唯一不变的id作为搜索条件
            var sqllen = 'UPDATE syspersonlist SET name= "'+req.query.name+'",telphone = "'+req.query.telphone+'",email = "'+req.query.email+'" WHERE id = '+req.query.id
            conn.query(sqllen,(err,result) =>{
                if(err)  return console.log({msg:'更新失败，数据库出错',status:500})
                else res.send({msg:'更新成功！', status:200})
            })
        }
    })
}